package com.code.coinprice.configs;

import com.code.coinprice.consts.CommonConstant;
import org.apache.commons.codec.binary.StringUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

/**
 * 根据APP端请求头中的语言不同读取il8n下不同配置文件
 */
@Configuration
public class MutiLanguageLocaleConfig {

    /**
     * 自定义国际化解析器
     *
     * @return LocaleResolver
     */
    @Bean
    public LocaleResolver localeResolver() {
        return new MutiLanguageLocaleResolver();
    }


    public static class MutiLanguageLocaleResolver implements LocaleResolver {

        @Override
        public Locale resolveLocale(HttpServletRequest request) {
            String language = request.getHeader(CommonConstant.LANGUAGE);
            Locale locale = Locale.ROOT;
            if (StringUtils.equals(language, CommonConstant.ENG)) {
                locale = Locale.US;
            } else if (StringUtils.equals(language, CommonConstant.KH)) {
                locale = new Locale("pp", "KH");
            }
            return locale;
        }

        @Override
        public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
        }
    }

}
